﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

using Project.IManager;
using Project.IManager.Rights;
using Project.Repository.Rights;
using Project.Model.Rights;
using System.Web;
using Project.Repository;
using System.Web.Security;
using Project.Model;
using NHibernate.Criterion;
using Project.Common;

namespace Project.Manager.Rights
{
    public class UserManager : AbstractManager<User>, IUserManager
    {
		public IUserDao UserDao { get; set; }
        public IUserProfileDao UserProfileDao { get; set; }
        public IRoleDao RoleDao { get; set; }

        #region   用户登录、验证
        public virtual void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        public virtual void SetAuthCookie(string email, bool createPersistentCookie)
        {
            FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
        }

        public virtual string HashPasswordForStoringInConfigFile(string password)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
        }

        /// <summary>
        /// 用户登录验证
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="IsRememberMe">是否记住我</param>
        /// <returns>true:正确.false:错误</returns>
        public virtual bool Authenticate(string userName, string password, bool IsRememberMe)
        {
            // 不能用此方法,此方法需要配置web.config中的证书(不知如何配置)
            //return FormsAuthentication.Authenticate(userName,password);
            // 根据用户名查找用户表,之后验证密码是否一致
            User user = this.GetUserByName(userName);
            if (user != null && user.Password == this.HashPasswordForStoringInConfigFile(password))
            {
                // 设置登录信息
                this.SetAuthCookie(userName, IsRememberMe);
                return true;
            }
            else
            {
                return false;
            }
        }
        
        /// <summary>
        /// 获取当前用户  注意：context.Items["user"] 始终为 null，因此实际都从数据库中获取User
        /// </summary>
        /// <returns></returns>
        public virtual User CurrentUser()
        {
            User model = null;

            HttpContext context = HttpContext.Current;

            if (context.User == null) return null;
            if (!context.User.Identity.IsAuthenticated) return null;
            if (context.Items["user"] != null)
            {
                model = (User)context.Items["user"];

                //model.Code = "从HttpContext中获取";
            }
            else
            {
                model = this.Get(context.User.Identity.Name);
                context.Items.Add("user", model);

                //model.Code = "从数据中获取: " + context.User.Identity.Name;
            }

            return model;
        }
        #endregion

        //public User GetByName(string name)
        //{
        //   return Dao.GetByName(name);     

        //}

        // 用户免费试用
        public void FreeTrial(User user, UserProfile userProfile)
        {
            user.UserProfile = userProfile;
            userProfile.User = user;

            UserProfileDao.Save(userProfile);
        }

        // 通过用户名（邮箱）查找用户
		//public void GetByName(string name)
		//{
		//    UserDao.GetByName(name);
		//}

		public IList<User> GetAll(User searchModel)
		{
			return UserDao.GetAll(searchModel);
		}

        /// <summary>
        /// 根据用户名查找用户
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public User GetUserByName(string UserName)
        {
            //创建查询器
            IList<ICriterion> queryList = new List<ICriterion>();
            //传入条件
            queryList.Add(Restrictions.Eq(PropertyNameHelper.Resolve<User>(d => d.Name), UserName));

            IList<User> list = UserDao.GetByCriteria(queryList);

            if (list != null && list.Count == 1)
            {
                return list[0];
            }
            else
            {
                return null;
            }

        }

    }
}
